<template>
	<el-drawer v-model="visible" size="100%" :show-close="false">
		<template #header="{ close, titleId, titleClass }">
			<span :id="titleId" :class="titleClass">{{ title }}</span>
			<div class="action-bar">
				<!-- <el-button icon="el-icon-refresh" type="text" @click="refresh">刷新</el-button> -->
				<el-button type="primary" @click="saveDataForm">确定</el-button>
				<el-button class="btnReturn" @click="close">返回</el-button>
			</div>
		</template>
		<el-scrollbar class="layout-scrollbar">
			<div id="data-form" style="width: 100%">
				<el-alert title="属性编辑" type="info" :closable="false" style="background-color: #f7f8fa; color: #1d2129" />
				<el-form ref="dataFormRef" :model="dataForm" label-width="110px" :rules="dataRule" v-loading="formLoading">
					<el-form-item label="标签名称" prop="zhmc">
						<el-input v-model="dataForm.zhmc" placeholder="请输入标签名称" />
						<!-- <span class="tip">必填,长度在6-20之间</span> -->
					</el-form-item>
					<el-form-item label="适用标签" prop="tip">
						<el-tag v-for="(item, index) in bqbhSelDataList" :key="index">{{ item.name }}</el-tag>
						<el-button class="button-new-tag" @click="showInput">+ 编辑标签</el-button>
					</el-form-item>
					<el-form-item label="标签属性" prop="bqsx">
						<el-input type="textarea" :rows="2" placeholder="请输入标签属性" v-model="dataForm.bqsx"> </el-input>
					</el-form-item>
					<el-form-item label="风险等级" prop="fxdj">
						<el-select v-model="dataForm.fxdj" placeholder="请选择风险等级" style="width: 100%">
							<el-option :value="'1'" :label="'无风险'"></el-option>
							<el-option :value="'2'" :label="'低风险'"></el-option>
							<el-option :value="'3'" :label="'中风险'"></el-option>
							<el-option :value="'4'" :label="'高风险'"></el-option>
						</el-select>
					</el-form-item>
					<el-row :gutter="10">
						<el-col :span="6">
							<div class="grid-content bg-purple">
								<el-form-item label="生效方式" prop="sxfs">
									<el-radio-group v-model="dataForm.sxfs">
										<el-radio label="2">单次</el-radio>
										<el-radio label="1">长期</el-radio>
									</el-radio-group>
								</el-form-item>
							</div>
						</el-col>
					</el-row>
					<el-form-item label="标签对象" prop="bqdxbh">
						<el-select v-model="dataForm.bqdxbh" placeholder="请选择标签对象" style="width: 100%">
							<el-option :value="'1'" :label="'患者'"></el-option>
							<el-option :value="'2'" :label="'医生'"></el-option>
							<el-option :value="'3'" :label="'机构'"></el-option>
							<el-option :value="'4'" :label="'科室'"></el-option>
							<el-option :value="'5'" :label="'事件'"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="是否入库" prop="sflk">
						<el-radio-group v-model="dataForm.sflk">
							<el-radio :label="'1'">是</el-radio>
							<el-radio :label="'2'">否</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
				<el-alert title="规则维护" type="info" :closable="false" style="background-color: #f7f8fa; color: #1d2129" />
				<div style="padding: 10px 0">
					<el-button type="primary" :icon="Plus" @click="addRuleFirst()" style="margin-bottom: 10px">新增规则 </el-button>
					<Configure ref="configureRef"></Configure>
				</div>
			</div>
		</el-scrollbar>

		<template v-if="inputVisible">
			<LabelSelect ref="labelSelectRef" :value="bqbhSelData" @confirm="labelConfirm"></LabelSelect>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { combinationDetail, getLabelListAll, combinationSave } from '@/api/labels-mana/index'
import Configure from './configure.vue'
import LabelSelect from './labelSelect.vue'
const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataFormRef = ref()
const formLoading = ref(false)
const dataForm = reactive({
	sxfs: '',
	sflk: '',
	fxdj: '',
	bqdxbh: '',
	bqdjid: '',
	cfsj: '',
	bqsx: '',
	bqbh: '',
	zhmc: '',
	zhbh: '',
	creator: JSON.parse(sessionStorage.getItem('userInfo')).id,
	orgCode: JSON.parse(sessionStorage.getItem('userInfo')).orgCode
})

const title = ref('')

const dataRule = ref({
	zhmc: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
	sflk: [{ required: true, message: '请选择是否入库', trigger: 'change' }]
})

const inputVisible = ref(false)

const configureRef = ref()

const bqbhSelData = ref([])
const bqbhSelDataList = ref([])

const andList = ref([])
const orList = ref([])

const labelSelectRef = ref()
const showInput = () => {
	inputVisible.value = true
	nextTick(() => {
		labelSelectRef.value.init()
	})
}

const init = (data?: any, treeId?: string) => {
	bqbhSelData.value = []
	bqbhSelDataList.value = []
	andList.value = []
	orList.value = []
	visible.value = true

	title.value = '新增'

	dataForm.creator = JSON.parse(sessionStorage.getItem('userInfo')).id

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	dataForm.bqdjid = treeId + ''

	if (data) {
		title.value = data.zhmc ? data.zhmc + '的编辑' : '编辑'
		getCategory(data.zhbh)
	} else {
		getLabelList()
	}
}

const bqbhData = ref([])
// 获取所有的标签
const getLabelList = async () => {
	await getLabelListAll().then(res => {
		bqbhData.value = res.data
		for (let i = 0; i < bqbhSelData.value.length; i++) {
			res.data.forEach(element => {
				if (element.bqbh == bqbhSelData.value[i]) {
					bqbhSelDataList.value.push({
						name: element.bqmc,
						value: element.bqbh
					})
				}
			})
		}
	})
}

const getBqbhSelDataList = () => {
	bqbhSelDataList.value = []
	for (let i = 0; i < bqbhSelData.value.length; i++) {
		bqbhData.value.forEach(element => {
			if (element.bqbh == bqbhSelData.value[i]) {
				bqbhSelDataList.value.push({
					name: element.bqmc,
					value: element.bqbh
				})
			}
		})
	}

	initConfig()
}

const getCategory = async (id: any) => {
	await combinationDetail({ zhbh: id }).then(res => {
		Object.assign(dataForm, res.data)
		if (dataForm.bqbh) {
			dataForm.bqbh.split(',').forEach(element => {
				bqbhSelData.value.push(element)
			})

			if (dataForm.bqgzand) {
				const bqgzand = dataForm.bqgzand

				const andS = bqgzand.split(',')
				andS.forEach(item => {
					andList.value.push(item)
				})
			}

			if (dataForm.bqgzor) {
				const bqgzor = dataForm.bqgzor
				const orS = bqgzor.split(',')
				orS.forEach(item => {
					orList.value.push(item)
				})
			}
		} else {
			bqbhSelData.value = []
		}

		getLabelList()

		initConfig()
	})
}

const addRuleFirst = () => {
	configureRef.value.addConfig(bqbhSelDataList.value)
}

const initConfig = () => {
	configureRef.value.initConfigData(andList.value, orList.value, bqbhSelDataList.value)
}

const labelConfirm = value => {
	bqbhSelData.value = value

	getBqbhSelDataList()
}

const saveDataForm = () => {
	let AndList = ''
	let OrList = ''

	if (configureRef.value.configureList.length) {
		const configList = configureRef.value.configureList
		AndList = configList[0].condition
		OrList = ''
		configList.forEach((element, index) => {
			if (index) {
				if (element.symbol === 'OR') {
					if (OrList) {
						OrList = OrList + ',' + element.condition
					} else {
						OrList = element.condition
					}
				} else if (element.symbol === 'AND') {
					AndList = AndList + ',' + element.condition
				}
			}
		})
	}
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

		dataForm.bqgzand = AndList
		dataForm.bqgzor = OrList

		if (dataForm.zhbh) {
			dataForm.bqbh = bqbhSelData.value.join(',')
		}

		combinationSave(dataForm).then(res => {
			console.log(res)
			if (res.data.bz == '1') {
				ElMessage({
					message: res.msg,
					type: 'success',
					duration: 500,
					onClose: () => {
						visible.value = false
						emit('refreshDataList')
					}
				})
			} else {
				ElMessage({
					message: res.msg,
					type: 'error',
					duration: 500,
					onClose: () => {}
				})
			}
		})
	})
}

defineExpose({
	init
})
</script>

<style lang="scss">
.el-tag + .el-tag {
	margin-left: 16px;
}

#data-form .el-form {
	margin-top: 10px;
}

.el-drawer__body {
	padding: 0;
}

.action-bar {
	float: right;
}

.button-new-tag {
	margin-left: 16px;
	height: 32px;
	line-height: 30px;
	padding-top: 0;
	padding-bottom: 0;
}
</style>